/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jsf;

import java.io.IOException;
import java.security.Principal;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import jpa.entities.User;

/**
 *
 * @author andreas
 */
@ManagedBean
@RequestScoped
public class LoginController {

    /** Creates a new instance of LoginController */
    public LoginController() {
    }

    @EJB
    private jpa.session.UserFacadeRemote userFacade;

    private User user; // The JPA entity.

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userFacade.find(new Integer(principal.getName())); // Find User by j_username.
            }
        }
        return user;
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        ((HttpSession) externalContext.getSession(true)).invalidate();
        externalContext.redirect("index.xhtml");
    }

}
